package dictdata

import (
	"context"
	"net/http"

	"go-zero-admin/apps/system/cmd/api/internal/svc"
	"go-zero-admin/apps/system/cmd/api/internal/types"
	"go-zero-admin/apps/system/cmd/rpc/syspb"
	"go-zero-admin/pkg/constant"

	"github.com/duke-git/lancet/v2/convertor"
	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetDictDataListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
	r      *http.Request
}

func NewGetDictDataListLogic(ctx context.Context, svcCtx *svc.ServiceContext, r *http.Request) *GetDictDataListLogic {
	return &GetDictDataListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
		r:      r,
	}
}

func (l *GetDictDataListLogic) GetDictDataList(req *types.GetDictDataListReq) (resp *types.GetDictDataListResp, err error) {
	// 查询出字典类型
	dictTypeListResp, err := l.svcCtx.DictTypeRpc.GetDictTypeList(l.ctx, &syspb.GetDictTypeListReq{
		DictType: req.DictType,
		Status:   convertor.ToString(constant.DictDataStatusOn),
	})
	if err != nil {
		return nil, err
	}
	// 如果没有字典类型或者字典类型禁用，则返回空
	if len(dictTypeListResp.GetList()) == 0 {
		return &types.GetDictDataListResp{
			List: make([]*types.SysDictData, 0),
		}, nil
	}

	// 查询出字典数据
	listResp, err := l.svcCtx.DictDataRpc.GetDictDataList(l.ctx, &syspb.GetDictDataListReq{
		DictTypeList: []string{req.DictType},
		Status:       convertor.ToString(constant.DictDataStatusOn),
	})
	if err != nil {
		return nil, err
	}

	// 处理数据
	dictDataList := make([]*types.SysDictData, 0)
	for _, v := range listResp.GetList() {
		var dictData types.SysDictData
		_ = copier.Copy(&dictData, v)
		dictDataList = append(dictDataList, &dictData)
	}

	return &types.GetDictDataListResp{
		List: dictDataList,
	}, nil
}
